package com.itfreer.data.general.utils;

import com.itfreer.data.general.RowBase;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * 定义JSON转换
 * @author chenxu
 *
 */
public class JSONConvertUtils {
	
	/**
	 * 将JSON转换为对象
	 * @param row
	 * @return
	 */
	public static RowBase convertToEntity(String row){
		ObjectMapper mapper = new ObjectMapper();
		JsonNode rootNode;
		try {
			rootNode = mapper.readTree(row);
			RowBase entity = mapper.readValue(rootNode, RowBase.class);
			setChildTable(mapper, rootNode, entity);
			return entity;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static void setChildTable(ObjectMapper mapper, JsonNode rootNode, RowBase entity) throws JsonParseException, JsonMappingException, IOException{
		JsonNode childNode = rootNode.get("childValues");
		if(childNode!=null){
			Iterator<String> fieldNames = childNode.getFieldNames();
			while(fieldNames.hasNext()){
				String childTable = fieldNames.next();
				JsonNode childRowListNode = childNode.get(childTable);
				Iterator<JsonNode> rowListNode = childRowListNode.getElements();
				List<RowBase> cRowList = new ArrayList<RowBase>();
				while(rowListNode.hasNext()){
					JsonNode rowNode = rowListNode.next();
					RowBase cRow = mapper.readValue(rowNode, RowBase.class);
					cRowList.add(cRow);
					
					setChildTable(mapper, rowNode, cRow);
				}
				if(entity.getChildValues()==null){
					entity.setChildValues(new HashMap<String, List<RowBase>>());
				}
				entity.getChildValues().put(childTable, cRowList);
			}
		}
	}
}
